from django.shortcuts import render
from django.contrib.auth.models import User
from django.http import HttpResponse
from use.form import NewUser
import datetime
from django.contrib.auth.hashers import make_password
from django.contrib.auth.views import LoginView, LogoutView
from use.models import VisitorRecord
import logging

logger = logging.getLogger(__name__)


def VisitorInf(request):
    try:
        if 'HTTP_X_FORWARDED_FOR' in request.META:
            current_ip = request.META.get('HTTP_X_FORWARDED_FOR')
        else:
            current_ip = request.META.get('REMOTE_ADDR')
        current_page = request.get_full_path()
        VisitorRecord.objects.create(day=datetime.datetime.now(), ip=current_ip, page=current_page)
        logger.info('insert a visitor logs')
    except Exception as e:
        logger.error('the vistors info has error:%s' % str(e))
        print('the vistors info has error:%s' % str(e))


class MyLogin(LoginView):
    template_name = 'Login.html'
    redirect_field_name = 'Hello'


class MyLogout(LogoutView):
    template_name = 'Logout.html'


# Create your views here.
def Login1(request):
    if request.method == 'POST':
        u = request.POST.get('username', '')
        p = make_password(request.POST.get('password', ''))
        s = request.POST.get('is_superuser', '')
        e = request.POST.get('email', '')
        now_date = datetime.datetime.now()
        if s == 'on':
            new_date = dict(username=u, password=p, is_staff=1, is_superuser=1, last_login=now_date, email=e)
        else:
            new_date = dict(username=u, password=p, is_staff=1, is_superuser=0, last_login=now_date, email=e)
        use1 = User.objects.create_user(**new_date)
        use1.save()
        return HttpResponse('user created!')
    else:
        user = NewUser(instance=None)
        return render(request, 'newuser.html', locals())


def updatePassword(request):
    VisitorInf(request)
    if request.method == 'POST':
        u = request.POST.get('username', '')
        p = request.POST.get('password', '')
        newP = User.objects.filter(username=u).first()
        if newP:
            newP.set_password(p)
            newP.save()
            return HttpResponse('password is changed')
        else:
            return HttpResponse('no such user' + u)
    else:
        user = NewUser(instance=None)
        return render(request, 'updatePassword.html', locals())


def deleteUser(request):
    if request.method == 'POST':
        u = request.POST.get('username', '')
        newP = User.objects.filter(username=u).first()
        if newP:
            newP.delete()
            return HttpResponse('the user is deleted')
        else:
            return HttpResponse('no such user' + u)
    else:
        user = NewUser(instance=None)
        return render(request, 'deleteUser.html', locals())


def testSession(request):
    request.session['username'] = 9999
    request.session.setdefault('username', 9999)
    print(request.session['username'])
    print(request.session.get('username', ''))

    print(request.session.keys())
    print(request.session.values())
    print(request.session.items())

    print(request.session.session_key)

    request.session.clear_expired()

    request.session.exists('session_key')

    request.session.set_expiry(1000)
    request.session.get_expiry_age()
    request.session.get_expiry_date()

    del request.session['username']

    request.session.delete('session_key')
    request.session.clear()
    return HttpResponse('ok')
